//
//  DealerTableViewController.m
//  CarHome
//
//  Created by lanou3g on 15-5-2.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "DealerTableViewController.h"
#import "Dealer.h"
#import "Dealers.h"
#import "DealerTableViewCell.h"

@interface DealerTableViewController ()

@property (nonatomic, retain) NSMutableArray *dealerlist;
@property (nonatomic, retain) Dealers *ds;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pagecount;

@end

@implementation DealerTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"DealerTableViewCell" bundle:nil] forCellReuseIdentifier:@"DealerTableViewControllerIdentifier"];
//    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadData)];
//    [self.tableView.header beginRefreshing];
    self.dealerlist = [NSMutableArray array];
}

- (void)loadData {
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.tableView.header beginRefreshing];
}

- (void)loadNewData {
    __block typeof(self) weakSelf = self;
    if (_dealerlist.count == 0) {
        self.page = 1;
        NSLog(@"%@", DealerURLwithCarIDAndPageNum(_seriesID, _page));
        [HTTPRequest requestWithURL:DealerURLwithCarIDAndPageNum(_seriesID, _page++) method:@"GET" result:^(NSData *data) {
            NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            self.ds = [[Dealers new] autorelease];
            [_ds setValuesForKeysWithDictionary:dict[@"result"]];
            
            self.pagecount = [_ds.pagecount intValue];
            if (_pagecount != 0) {
                [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
                self.dealerlist = [[NSMutableArray alloc]initWithArray:_ds.dealerlist];
                [weakSelf.tableView reloadData];
            } else {
                [self.tableView.header setTitle:@"No more data" forState:MJRefreshHeaderStateIdle];
            }
            [self.tableView.header endRefreshing];
        }];
        [self.tableView.header beginRefreshing];
        
    } else {
        [self.tableView reloadData];
    }
}

- (void)loadMoreData {
    if (_page >= _pagecount) {
        __block typeof(self) weakSelf = self;
        NSLog(@"%@", DealerURLwithCarIDAndPageNum(_seriesID, _page));
        
        [HTTPRequest requestWithURL:DealerURLwithCarIDAndPageNum(_seriesID, _page++) method:@"GET" result:^(NSData *data) {
            NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            self.ds = [[Dealers new] autorelease];
            
            [_ds setValuesForKeysWithDictionary:dict[@"result"]];
            
            _dealerlist = _ds.dealerlist;
            
            [weakSelf.tableView reloadData];
            [self.tableView.footer noticeNoMoreData];
        }];
    }
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dealerlist.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DealerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DealerTableViewControllerIdentifier" forIndexPath:indexPath];
    Dealer *d = _dealerlist[indexPath.row];
    
    cell.name.text = d.name;
    cell.address.text = d.address;
    
    return cell;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return 180;
//}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
